package net.wenku8.reader.view.online

import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.lazy.rememberLazyListState
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.snapshotFlow
import androidx.lifecycle.viewmodel.compose.viewModel
import net.wenku8.reader.LocalNavController
import net.wenku8.reader.enums.RouteOnlineReviewFollow
import net.wenku8.reader.state.StateReadOnline
import net.wenku8.reader.ui.lite.LiteCard
import net.wenku8.reader.ui.lite.LiteLabel
import net.wenku8.reader.ui.lite.LiteLine
import net.wenku8.reader.ui.lite.LitePanel
import net.wenku8.reader.ui.lite.LiteText
import net.wenku8.reader.ui.theme.LiteBlue
import net.wenku8.reader.ui.theme.LiteRed
import androidx.compose.runtime.collectAsState

@Composable
fun OnlineReviewList() {
    val onlineReviewListViewModel = viewModel<OnlineReviewListViewModel>()
    val navController = LocalNavController.current
    LaunchedEffect(Unit) {
        onlineReviewListViewModel.initData()
    }
    val listState = rememberLazyListState()
    LaunchedEffect(listState) {
        snapshotFlow { listState.layoutInfo.visibleItemsInfo.lastOrNull() }
            .collect { lastVisibleItem ->
                if (lastVisibleItem != null && lastVisibleItem.index >= onlineReviewListViewModel.dataList.size - 1) {
                    // 当最后一个可见项是倒数第二个或更靠后时，触发加载更多
                    onlineReviewListViewModel.loadNextPage()
                }
            }
    }
    LitePanel(
        hostState = onlineReviewListViewModel.hostState,
        title = "书评列表",
        backNav = true
    ) {
        Column {
            LiteLine{
                Row {
                    LiteLabel("书名:")
                    LiteLabel("[" + StateReadOnline.bookName.collectAsState().value + "]", color = LiteRed)
                }
            }
            LazyColumn(state = listState){
                items(items = onlineReviewListViewModel.dataList) { dataValue ->
                    LiteCard(
                        onClick = {
                            StateReadOnline.reviewId.value = dataValue.reviewId
                            StateReadOnline.reviewTitle.value = dataValue.reviewContentValue.value
                            navController.navigate(RouteOnlineReviewFollow)
                        },
                        indent = 0,
                        header = {
                            LiteText("[" + dataValue.reviewUserValue.name + "]:", color = LiteBlue)
                        }
                    ){
                        LiteText(dataValue.reviewContentValue.value, showAll = true)
                    }
                }
            }
        }
    }
}
